package com.jn.erp.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.time.Duration;

/**
 * <pre>
 *
 * </pre>
 *
 * @author sunjiyong
 * @since 2024/1/10 15:16
 */
@Slf4j
@Component
public class RedisLock {

    @Autowired
    private RedisTemplate redisTemplate;


    public Boolean lock(String key) {
        ValueOperations<String, String> valueOps = redisTemplate.opsForValue();
        Boolean aBoolean =  valueOps.setIfAbsent(key, "task", Duration.ofMinutes(5));
        return aBoolean;
    }


    public Boolean lockBySeconds(String key,long timeOut) {
        ValueOperations<String, String> valueOps = redisTemplate.opsForValue();
        Boolean aBoolean =  valueOps.setIfAbsent(key, "task", Duration.ofSeconds(timeOut));
        return aBoolean;
    }

    public Boolean del(String key) {
        return redisTemplate.delete(key);
    }

}
